package me.zingon.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;

import me.zingon.dao.ClazzDao;
import me.zingon.dao.TradDao;
import me.zingon.dao.UserDao;
import me.zingon.model.Clazz;
import me.zingon.model.Trad;
import me.zingon.model.User;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.web.util.HtmlUtils;
// import top.rinpsi.tools.ImgDeal;

@Service
@Scope("session")
public class UserService {

	@Autowired
	ClazzDao clazzDao;

	@Autowired
	TradDao tradDao;

	@Autowired
	UserDao userDao;

	@Autowired
	NetService netService;

    // @Autowired
    // ImgDeal imgDeal;

	@Autowired
	EmailService emailService;

	@Autowired
	Properties msg;

	//测试学校图书馆验证码
    // public String getCode() throws Exception {
    //     return imgDeal.getCode(netService.myGet("http://222.192.62.8/reader/captcha.php",null).getEntity().getContent());
    // }

    public List<User> getUsers() {
		return userDao.getUsers();
	}

	public User login(User user){
		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		user.setRinpsipd(md5.encodePassword(user.getRinpsipd(),null));
		return userDao.login(user);
	}
	/**
	 * 测试是不是学生.相当于注册功能 是,就保存
	 * 
	 * @param xh
	 * @param sfzh
	 * @param pwd
	 * @param yzm
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@Transactional(propagation = Propagation.REQUIRED , rollbackFor = Exception.class)
	public User testUser(String xh, String sfzh, String pwd, String yzm, String ip)
			throws IOException {
		User user = userDao.getUserByStuid(xh);
		if (user != null) {
			// 已经存在
			User newUser = new User();
			newUser.setId(user.getId());
			newUser.setStuId(user.getStuId().equals(xh) ? null : xh);
			newUser.setCitizenId(user.getCitizenId().equals(sfzh) ? null : sfzh);
			newUser.setPassward(user.getPassword().equals(pwd) ? null : pwd);
			newUser.setIp(user.getIp().equals(ip) ? null : ip);
			newUser.setUpdateDate(new Timestamp(new Date().getTime()));
			userDao.updateUserInfo(newUser);
			return userDao.getUserByStuid(xh);
		}
		if (!netService.testUser(xh, sfzh, pwd, yzm).contains("Object moved to"))
			// 不是学生
			return null;
		// 第一次登陆
		int clazzId;
		List<String> list = netService.getBaseinfo();
		if(list.size()<2)
			//网络出错
			return null;
		Clazz clazz = new Clazz();
		clazz.setName(list.get(2));
		Clazz temp = clazzDao.getIdByName(clazz);
		if (temp != null)
			clazzId = temp.getId();
		else {
			clazzDao.insertClazz(clazz);
			clazzId = clazz.getId();
		}

		int tradId = 0;
		Trad trad = new Trad();
		trad.setName(list.get(3));
		Trad t = tradDao.getIdByName(trad);
		if (t != null) {
			tradId = t.getId();
		} else {
			tradDao.insertTrad(trad);
			tradId = trad.getId();
		}

		User u = new User();
		u.setStuId(xh);
		u.setName(list.get(0));
		u.setCitizenId(sfzh);
		u.setPassward(pwd);
		u.setClassId(clazzId);
		u.setTradId(tradId);
		u.setCreateDate(new Timestamp(new Date().getTime()));
		u.setUpdateDate(new Timestamp(new Date().getTime()));
		u.setIp(ip);
		u.setActivedUuid(UUID.randomUUID().toString());
		u.setActivedFlag(false);
		u.setDeletedFlag(0);
		userDao.insertUser(u);
		return u;

	}

	public String getScore(String startPage, String pageSize) throws IOException {
		return netService.getScore(startPage, pageSize);
	}

	public void getYzm(HttpServletResponse res) throws URISyntaxException, IOException {
		netService.myGetYzm(res);
	}

	public String getTrad(int id) {
		return tradDao.getNameById(id);
	}

	public String getClazz(int id) {
		return clazzDao.getNameById(id);
	}

	public String getPjInfo() throws IOException {
		return netService.getPjInfo();
	}

	public void pj(String cjids, String choose) throws IOException {
		if (cjids.length() > 0) {
			String[] ids = cjids.substring(0, cjids.length() - 1).split(",");
			netService.pj(ids, choose);
		}
	}

	@Transactional(propagation = Propagation.REQUIRED , rollbackFor = Exception.class)
    public int register(User user) {
		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		if(user.getRinpsipd()!=null&&!user.getRinpsipd().equals(""))
			user.setRinpsipd(md5.encodePassword(user.getRinpsipd(),null));
		user.setNickname(HtmlUtils.htmlEscape(user.getNickname()));
		user.setEmail(HtmlUtils.htmlEscape(user.getEmail()));
		user.setRinpsipd(HtmlUtils.htmlEscape(user.getRinpsipd()));
		user.setQq(HtmlUtils.htmlEscape(user.getQq()));
		user.setWeixin(HtmlUtils.htmlEscape(user.getWeixin()));
		user.setPhone(HtmlUtils.htmlEscape(user.getPhone()));
        return userDao.updateUserInfo(user);
    }

	@Transactional(propagation = Propagation.REQUIRED , rollbackFor = Exception.class)
	public int activeUser(String email, String uuid) throws UnsupportedEncodingException {
		email=new String(Base64Utils.decodeFromString(email),"utf-8");
		return userDao.activeUser(HtmlUtils.htmlEscape(email),uuid);
	}

	public void sendActiveEmail(HttpServletRequest req,User u){
		String[] requesturl=req.getRequestURL().toString().split("/");
		String url=requesturl[0]+"//"+requesturl[2]+req.getContextPath()+"/user/active/"
				+ Base64Utils.encodeToString(u.getEmail().getBytes())
				+"/"+u.getActivedUuid();
		emailService.sendActiveEmail(u.getEmail(),
				msg.getProperty("regEmail")
						.replace("{0}",url),null);
	}


	public String loginNtuByYzm(User user,String yzm) throws IOException {
		if(netService.testUser(user.getStuId(), user.getCitizenId(), user.getPassword(), yzm).contains("Object moved to"))
			return "success";
		return "error";
	}
}
